using UnityEngine;
using System;

public class AdsManager : MonoBehaviour
{
    public static AdsManager Instance { get; private set; }

    // 广告组件引用
    private JiLiAd rewardAd;
    private ChaPingAd interstitialAd;

    // 回调事件
    public event Action OnSdkInitialized;
    public event Action<string, MaxSdkBase.AdInfo> OnRewardedAdCompleted;
    public event Action OnRewardedAdFailed;
    public event Action OnInterstitialAdCompleted;
    public event Action OnInterstitialAdFailed;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void InitializeAds()
    {
        // 注册 SDK 初始化回调
        MaxSdkCallbacks.OnSdkInitializedEvent += OnMaxSdkInitialized;

        // 初始化 MAX SDK
        MaxSdk.InitializeSdk();

        Tools.Log("Max===>", "初始化Max");
    }

    private void OnMaxSdkInitialized(MaxSdkBase.SdkConfiguration config)
    {
        Tools.Log("Max===>", "Max初始化成功");

        // 初始化广告组件
        InitializeRewardedAds();
        InitializeInterstitialAds();

        // 触发初始化完成事件
        OnSdkInitialized?.Invoke();
    }

    #region Rewarded Ads
    private void InitializeRewardedAds()
    {
        rewardAd = gameObject.AddComponent<JiLiAd>();
        rewardAd.OnAdCompleted += (string adUnitId, MaxSdkBase.AdInfo adInfo) =>
        {
            OnRewardedAdCompleted?.Invoke(adUnitId, adInfo);
        };
        rewardAd.OnAdFailed += () =>
        {
            OnRewardedAdFailed?.Invoke();
        };
        rewardAd.initRewardAd();
    }

    public void ShowRewardedAd()
    {
        if (rewardAd != null && rewardAd.IsRewardedAdReady())
        {
            rewardAd.ShowRewardedAd();
        }
        else
        {
            Tools.Log("激励广告", "未准备好");
            OnRewardedAdFailed?.Invoke();
        }
    }
    #endregion

    #region Interstitial Ads
    private void InitializeInterstitialAds()
    {
        interstitialAd = gameObject.AddComponent<ChaPingAd>();
        interstitialAd.OnAdCompleted += () =>
        {
            OnInterstitialAdCompleted?.Invoke();
        };
        interstitialAd.OnAdFailed += () =>
        {
            OnInterstitialAdFailed?.Invoke();
        };
        interstitialAd.initIntAd();
    }

    public void ShowInterstitialAd()
    {
        if (interstitialAd != null && interstitialAd.IsInterstitialAdReady())
        {
            interstitialAd.ShowInterstitialAd();
            Tools.Log("插屏广告", "播放插屏广告");
        }
        else
        {
            Tools.Log("插屏广告", "未加载好");
            //关闭蒙版
            Tools.HideAdsPanel();
            OnInterstitialAdFailed?.Invoke();
        }
    }
    #endregion

    // 检查广告是否准备好
    public bool IsRewardedAdReady() => rewardAd != null && rewardAd.IsRewardedAdReady();
    public bool IsInterstitialAdReady() => interstitialAd != null && interstitialAd.IsInterstitialAdReady();
}